package com.ruoyi.traplight.domain;

import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class BufferedImageMultipartFile implements MultipartFile {
    private final BufferedImage image;
    private final String name;
    private final String originalFilename;


    public BufferedImageMultipartFile(BufferedImage image, String name,String originalFilename) {
        this.image = image;
        this.name = name;
        this.originalFilename = originalFilename;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        // 可以根据图片格式设置内容类型，比如JPEG图片的内容类型是 "image/jpeg"。
        // 为了简单起见，我们假设内容类型总是 "image/jpeg"。
        return "image/jpeg";
    }

    @Override
    public boolean isEmpty() {
        return image == null;
    }

    @Override
    public long getSize() {
        if (image == null) {
            return 0;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", bos);
            return bos.size();
        } catch (IOException e) {
            return 0;
        }
    }

    @Override
    public byte[] getBytes() throws IOException {
        if (image == null) {
            return new byte[0];
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", bos);
            return bos.toByteArray();
        }
    }

    @Override
    public InputStream getInputStream() throws IOException {
        if (image == null) {
            return null;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(image, "jpg", bos);
            return new ByteArrayInputStream(bos.toByteArray());
        }
    }

    @Override
    public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
        if (image == null) {
            throw new IllegalStateException("不能传输一个空文件");
        }
        ImageIO.write(image, "jpg", dest);
    }
}
